﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SSN.WebFramework;
using SSN.WebFramework.Security;

namespace SSN.WebFramework
{
    public abstract class AuthPage : GenPage
    {
        private UserManager _UserManager;
        public UserManager UserManager
        {
            get
            {
                if (_UserManager == null)
                {
                    _UserManager = new UserManager(SecurityManager.SecurityContext);
                }

                return _UserManager;
            }
        }

        /// <summary>
        /// TODO: Implement new access level stuff.
        /// </summary>
        public AccessLevel CurrentAccessLevel
        {
            get
            {
                return AccessLevel.All;
            }
        }

        /// <returns></returns>
        public override bool CheckSecurity()
        {
            if (!SecurityManager.IsLoggedIn)
            {
                LoggedUrl = Page.Request.Url.OriginalString;

                if (WebSettings.SecurityType == WebLoginType.UserPass)
                {
                    Response.Redirect(WebSettings.LogInPage);
                }
                else
                {
                    Response.Redirect(ErrorManager.NotAuthorizedPage);
                }
            }
            else if (WebSettings.SecurityType == WebLoginType.UserPass)// && SecurityManager.NeedsPasswordChange)
            {
                LoggedUrl = Page.Request.Url.OriginalString;
                //Response.Redirect(ParameterManager.EncryptUrlFormat("{0}?required=true", WebSettings.ChangePasswordPage));
            }


            if (!PageSecurityManager.CanView(this))
            {
                Response.Redirect(ErrorManager.NotAuthorizedPage);
            }
            /// TODO: Implement new security features.
            //if (!string.IsNullOrEmpty(RequiredRole) && RequiredRole != "*")
            //{
            //    if (!SecurityManager.IsInRole(RequiredRole))
            //        NotAuthorized();
            //}

            //if (!string.IsNullOrEmpty(RequiredEditRole) && RequiredEditRole != "*")
            //{
            //    CanEdit = SecurityManager.IsInRole(RequiredEditRole);
            //}

            return true;
        }

        public string EncryptUrl(string url)
        {
            string[] split = url.Split('?');
            return split[0] + ParameterManager.EncryptUrl("?" + split[1]);
        }
    }
}

